package com.lxr.test5002;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.lxr.test5002.base.BaseActivity;
import com.lxr.test5002.utils.MyUtil;
import com.sdk.devicemanager.ICcon;

import butterknife.BindView;

/**
 * 类描述:[板卡测试]
 * 说明:
 * 获取数据方式两种:
 * 直接返回
 * 接口回调
 *
 * @author: LXR-zsm
 * @Date: 2023/12/21 14:12
 */
public class TestPcieActivity extends BaseActivity implements View.OnTouchListener {
    private static final String TAG = TestPcieActivity.class.getSimpleName();
    @BindView(R.id.tv_pcie_status)
    TextView tvStatus;
    @BindView(R.id.btn_pcie_on)
    Button btnPcieOn;
    @BindView(R.id.btn_model)
    Button btnModel;
    @BindView(R.id.btn_get_data)
    Button btnGetData;
    @BindView(R.id.btn_port)
    Button btnPort;
    @BindView(R.id.btn_btl)
    Button btnBtl;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.btn_gpio)
    Button btnGpio;
    @BindView(R.id.btn_port_close)
    Button btnPortClose;
    @BindView(R.id.btn_pcie_off)
    Button btnPcieOff;
    boolean isRead = true;  //true  read方式 / false 回调方式
    String randData;

    public TestPcieActivity() {
        super(R.layout.activity_test_pcie);
    }

    private void updateStatus(String msg) {
        tvStatus.append(msg);
        tvStatus.append("\n");

        int scrollAmount = tvStatus.getLayout().getLineTop(tvStatus.getLineCount())
                - tvStatus.getHeight();
        if (scrollAmount > 0)
            tvStatus.scrollTo(0, scrollAmount);
        else
            tvStatus.scrollTo(0, 0);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvStatus.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvStatus.setText("当前数据通信方式" + (isRead ? "read" : "回调"));
    }

    @Override
    protected void initEvent() {
        btnPcieOn.setOnClickListener(view -> {
            //MCU：  1:上电  0：下电
            int ret = ICcon.getInstance().MCU_interface_power(1);
            updateStatus("板卡上电：" + (ret == 0 ? "成功" : "失败"));
        });

        btnBtl.setOnClickListener(view -> {
            boolean bandrate = ICcon.getInstance().setPCIBandrate(115200);
            updateStatus("设置串口波特率：" + (bandrate ? "成功" : "失败"));
        });

        btnPort.setOnClickListener(view -> {
            //打开/关闭串口
            //入口参数: var0：默认1，115200，var1: 0 关闭串口  1：打开串口
            //返回值:  int：0:打开成功  非0:打开失败
            int ret = ICcon.getInstance().oPenOrCloseSerialPort(1, 1);
            updateStatus("打开串口：" + (ret == 0 ? "成功" : "失败"));
        });
        btnSend.setOnClickListener(view -> {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //产生随机数据
                    randData = MyUtil.randomHexString(256);
                    if (isRead) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int len = ICcon.getInstance().PCI_CommandWrite(randData.length() / 2, MyUtil.hexToByteArr(randData), 200);
                                try {
                                    Thread.sleep(200);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                updateStatus("发送数据：len=" + len + "  " + (len == randData.length() / 2 ? "成功" : "失败"));
                            }
                        });
                    } else {
                        int len = ICcon.getInstance().onDataSent(MyUtil.hexToByteArr(randData));
                        updateStatus("发送数据：" + (len == 0 ? "成功" : "失败") +"  返回值："+len);
                    }
                }
            }).start();
        });
        btnGetData.setOnClickListener(view -> {
            String string = "";
            //读取串口数据
            byte[] pci_commandRead = ICcon.getInstance().PCI_CommandRead(128, 200, 100);
            if (pci_commandRead != null) {
                String s = MyUtil.bytesToString(pci_commandRead).replace(" ", "");
                string = string + s;
                updateStatus("接收数据长度:" + s.length() / 2);
                if (string.equals(randData)) {
                    updateStatus("数据匹配成功");
                } else {
                    updateStatus("数据匹配失败");
                }
            } else {
                updateStatus("读取数据为空");
            }
        });
        btnGpio.setOnClickListener(view -> {
            IOControl();
        });
        btnPortClose.setOnClickListener(view -> {
            int ret = ICcon.getInstance().oPenOrCloseSerialPort(1, 0);
            updateStatus("关闭串口：" + (ret == 0 ? "成功" : "失败"));

        });
        btnPcieOff.setOnClickListener(v -> {
            int ret = ICcon.getInstance().MCU_interface_power(0);
            updateStatus("板卡下电：" + (ret == 0 ? "成功" : "失败"));
        });

        btnModel.setOnClickListener(v -> {
            tvStatus.setText("");
            if (isRead = !isRead) {
                btnGetData.setVisibility(View.VISIBLE);
                ICcon.getInstance().closeSerialPort();
            } else {
                btnGetData.setVisibility(View.INVISIBLE);
                ICcon.getInstance().openReadThead();
                ICcon.getInstance().openSerialPort(new ICcon.OnOpenSerialPortListener() {
                    @Override
                    public void onSuccess(String s) {
                    }

                    @Override
                    public void onFail(String s, Status status) {

                    }
                }, bytes -> {
                    if (bytes != null) {
                        String s = MyUtil.bytesToString(bytes).replace(" ", "");
                        String string = s;
                        updateStatus("接收数据：" + s + "Len:" + s.length() / 2);
                        if (string.equals(randData)) {
                            updateStatus("数据匹配成功");
                        } else {
                            updateStatus("数据未匹配");
                        }
                    } else {
                        updateStatus("数据为空");
                    }
                });
            }
            updateStatus("当前数据通信方式" + (isRead ? "read" : "回调"));
        });
    }

    @Override
    protected void initData() {

    }

    private void IOControl() {
        //IO 拉高
        //8.4上电
        setGPIO(93, 1);
        setGPIO(94, 1);
        setGPIO(68, 1);
        powerOn_84();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //IO拉低
        //8.4下电
        setGPIO(93, 0);
        setGPIO(94, 0);
        setGPIO(68, 0);
        powerOff84();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //IO 拉高
        //3.3上电
        setGPIO(93, 1);
        setGPIO(94, 1);
        setGPIO(68, 1);
        powerOn_33();

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //IO拉低
        //3.3下电
        setGPIO(93, 0);
        setGPIO(94, 0);
        setGPIO(68, 0);
        powerOff33();

        //IO 拉高
        //8.4上电
        setGPIO(93, 1);
        setGPIO(94, 1);
        setGPIO(68, 1);
        powerOn_84();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void powerOff84() {
        int powerOff = ICcon.getInstance().exPowerOff();
        updateStatus("8.4下电：" + ((powerOff == 0 ? "成功" : "失败")));
    }

    private void powerOn_84() {
        int exPowerOn = ICcon.getInstance().exPowerOn();
        updateStatus("8.4上电：" + ((exPowerOn == 0 ? "成功" : "失败")));
    }

    private void powerOff33() {
        int powerOff = ICcon.getInstance().ex3PowerOff();
        updateStatus("3.3下电：" + ((powerOff == 0 ? "成功" : "失败")));
    }

    private void powerOn_33() {
        int exPowerOn = ICcon.getInstance().ex3PowerOn();
        updateStatus("3.3上电：" + ((exPowerOn == 0 ? "成功" : "失败")));
    }

    @SuppressLint("SetTextI18n")
    private void setGPIO(int GPIO, int statte) {
        int gpioState = ICcon.getInstance().setExGpio(GPIO, statte);
        updateStatus("GPIO：" + (statte == 0 ? "拉低" : "拉高") + "   结果：" + gpioState + "  " + ((gpioState == 1 ? "成功" : "失败")));
    }

    private float y1 = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            //按下去第一个Y坐标
            y1 = event.getY();
            //通知父控件不要干扰
            v.getParent().requestDisallowInterceptTouchEvent(true);
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (y1 - event.getY() > 50) {
                Log.e(TAG, "向上滑");
                v.getParent().requestDisallowInterceptTouchEvent(canVerticalScroll((TextView) v, true));
            } else if (event.getY() - y1 > 380) {
                Log.e(TAG, "向下滑: ");
                v.getParent().requestDisallowInterceptTouchEvent(canVerticalScroll((TextView) v, false));
            }

        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            v.getParent().requestDisallowInterceptTouchEvent(false);
        }
        return false;
    }

    /**
     * @param view 滑动的TextView
     * @param flag true 向上滑动 false 向下滑动
     * @return
     */
    protected boolean canVerticalScroll(TextView view, boolean flag) {
        //滚动的距离
        int scrollY = view.getScrollY();
        Log.e(TAG, "滚动距离: " + scrollY);
        //控件内容的总高度
        int scrollRange = view.getLayout().getHeight();
        Log.e(TAG, "控件内容的总高度: " + scrollRange);
        //控件实际显示的高度
        int scrollExtent = view.getHeight() - view.getCompoundPaddingTop() - view.getCompoundPaddingBottom();
        Log.e(TAG, "控件实际显示的高度: " + scrollExtent);
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;
        Log.e(TAG, "显示高度的差值: " + scrollDifference);
        if (flag) {
            return scrollDifference == scrollY ? false : true;
        } else {
            return scrollDifference == 0;
        }
    }
}